package com.itheima.reggie.Util;

import com.itheima.reggie.entity.Employee;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
/**
 * 自定义分页构造器
 */
@Data
public class Page {
    private List records;//每页员工数据
    private long total;//总员工数

    private int page;

    private int pageSize;

    private String name;//针对EmployeeController输入名字功能的属性

    public Page(List records, long total, int page, int pageSize, String name) {
        this.records = records;
        this.total = total;
        this.page = page;
        this.pageSize = pageSize;
        this.name = name;
    }

    public Page(List records, long total, int page, int pageSize) {
        this.records = records;
        this.total = total;
        this.page = page;
        this.pageSize = pageSize;
    }

    /**
     * 分页构造器PageConstructor,（静态方法）只要往此方法放入list列表与页码与一页的数据数量即可直接返回该页码对应的Page,其中Page.records就是该页的数据
     * 后续可进行改进（比如键入名称自动查找对应的数据Page等功能）
     */
    public static Page PageConstructor(List list,int page,int pageSize){
        int a = 0;
        List<Employee> records = new ArrayList<>();

        try {
            //records = employeeService.getAll().subList((page - 1) * pageSize, ((page - 1) * pageSize) + (pageSize - 1) + 1)中
            //当最后一页pageSize有x个但此时最后一页数据没有x个的时候, ((page - 1) * pageSize) + (pageSize - 1) + 1这串代码会使subList超出索引取值
            //需要抓取IndexOutOfBoundsException异常进行特殊处理
            list.get(((page - 1) * pageSize) + (pageSize - 1));
            //无异常的前提下,如果name为空,则将employee全部升序查出到list,按page与pageSize从list中截出所需列
            records = list.subList((page - 1) * pageSize, ((page - 1) * pageSize) + (pageSize - 1) + 1);
        }catch (IndexOutOfBoundsException e){
            if (list.size() % pageSize == 0){
                a = pageSize;
                records = list.subList((page - 1) * pageSize, ((page - 1) * pageSize) + (pageSize - 1) - pageSize + a + 1);
            }else {
                a = list.size() % pageSize;
                records = list.subList((page - 1) * pageSize, ((page - 1) * pageSize) + (pageSize - 1) - pageSize + a + 1);
            }
        }

        //构造分页构造器
       String name = null;
       return new Page(records,list.size(),page,pageSize,name);
    }
}
